#!/bin/sh
refname="$1"
oldrev="$2"
newrev="$3"

# /var/opt/gitlab/git-data/repositories/root/hehehaha.git/custom_hooks

# 打印参数
echo $refname
echo $oldrev
echo $newrev


# ========================================== <路径配置> ========================================== 
# 对完访问地址: 需要配置
# nginxHostPrefix="http://localhost"
# 本地 Nginx 静态网页路径
# nginxPathPrefix="D:/nginx/nginx-1.11.1/html"
# 变动文件拷贝程序 地址
# changeFileCopyJar="D:/workspace/repo/jgit-learn/target/jgit-learn-1.0-SNAPSHOT.jar"
# sonarlint Home
# sonarlintHome="D:/workspace/repo/sonarlint-cli/target"
# sonarlint 分析程序地址
# sonarlintJar="$sonarlintHome""/sonarlint-cli-2.0.jar"


# 对完访问地址: 需要配置
nginxHostPrefix="http://192.168.106.128"
# 本地 Nginx 静态网页路径
nginxPathPrefix="/opt/gitlab/embedded/service/gitlab-rails/public"
# 变动文件拷贝程序 地址
changeFileCopyJar="/root/sonarlit/sonarlint-copy/jgit-learn-1.0-SNAPSHOT.jar"
# sonarlint Home
sonarlintHome="/root/sonarlit/sonarlint-cli"
# sonarlint 分析程序地址
sonarlintJar="$sonarlintHome""/sonarlint-cli-2.0.jar"

# ========================================== </路径配置> ========================================== 

sonarlint="/sonarlint"
# 本地需要分析的源码地址
nginxSrcPath="$nginxPathPrefix""$sonarlint""/""$newrev""/src"
# 本地URL地址
nginxReportPath="$nginxPathPrefix""$sonarlint""/""$newrev""/report/index.html"
# 真实的报告URL地址
accessPath="$nginxHostPrefix""$sonarlint""/""$newrev""/report/index.html"

echo $nginxSrcPath
echo $nginxReportPath
echo $accessPath


# 判断是否是新创建的或者删除的分支
zero="0000000000000000000000000000000000000000"
if [ $oldrev = $zero -o $newrev = $zero ];then
	echo "创建或者删除分支不进行分析,已自动提交成功"
	exit 0
fi


# 获取分支名 只有 以 "dev_" 或者 "fixbug_" 开头的分支才会被分析
branchName=${refname##*/}
echo $branchName 

if [[ "$branchName" =~ ^dev_ || "$branchName" =~ ^fixbug_ ]]
then
	echo "$branchName 需要被分析"
else
	echo "$branchName 分析将被跳过,自动提交成功，只有 以 \"dev_\" 或者 \"fixbug_\" 开头的分支才会被分析"
	exit 0
fi


# 获取当期路径
gitDir=$(pwd)
echo $gitDir


# 获取变动的文件
changeFiles=$(git diff --name-only $oldrev $newrev | xargs )
echo $changeFiles


# 拷贝变动的文件
# java -jar $changeFileCopyJar $gitDir $newrev $nginxSrcPath $changeFiles


# 判断是否有文件拷贝
if [ ! -d "$nginxSrcPath" ]; then
	echo "没有需要分析的文件"
	exit 0
else	
	echo "文件拷贝完成，开始分析"
fi


# 分析程序程序
java -jar -Dsonarlint.home=$sonarlintHome -Dproject.home=$nginxSrcPath $sonarlintJar --src **/*.java --html-report $nginxReportPath --charset UTF-8
#java -jar -Dsonarlint.home=/home/kail/_ -Dproject.home=/home/kail/sonarResult/src /home/kail/_/sonarlint-cli-2.0.jar --src **/*.java --html-report /home/kail/sonarResult/report/index.html

if [ -f "$nginxReportPath" ]; then
	reportHtml=$(cat $nginxReportPath)
	if [[ "$reportHtml" =~ "No issues" ]]
	then
		echo "代码无问题"
	else
		echo "=========================================================================================================================="
		echo "您的代码有Bug，请查看分析报告: ""$accessPath"
		echo "=========================================================================================================================="
		exit 1
	fi
fi


exit 0
